﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace SensorJanken
{
    public partial class MainPage : PhoneApplicationPage
    {
        private const string groupnameKey = "groupname";
        private const string groupaddressKey = "groupaddress";
        private const string groupportKey = "groupport";

        // コンストラクター
        public MainPage()
        {
            InitializeComponent();

            var appSettings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
            if (!appSettings.Contains(groupnameKey))
            {
                appSettings.Add(groupnameKey, "jangen");
                appSettings.Add(groupaddressKey, "224.0.1.1");
                appSettings.Add(groupportKey, "52274");
            }
            tbGroupName.Text = appSettings[groupnameKey] as string;
            tbGroupAddress.Text = appSettings[groupaddressKey] as string;
            tbGroupPort.Text = appSettings[groupportKey] as string;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/PageJanken.xaml?NavigatedFrom=Main Page", UriKind.Relative));
        }

        private void ToAppearAlertPanel(string message)
        {
            tbAlert.Text = message;

            Storyboard sb = new Storyboard();
            sb.Duration = new Duration(TimeSpan.FromSeconds(1));
            DoubleAnimation da = new DoubleAnimation();
            da.Duration = new Duration(TimeSpan.FromSeconds(1));
            da.From = 0;
            da.To = 1;
            sb.Children.Add(da);
            Storyboard.SetTarget(da, alertPanel);
            Storyboard.SetTargetProperty(da, new PropertyPath(Grid.OpacityProperty));
            sb.Begin();

            buttonJoinAndStart.IsEnabled = false;
        }

        private void ToDisappearAlertPanel()
        {
            Storyboard sb = new Storyboard();
            sb.Duration = new Duration(TimeSpan.FromSeconds(1));
            DoubleAnimation da = new DoubleAnimation();
            da.Duration = new Duration(TimeSpan.FromSeconds(1));
            da.From = 1;
            da.To = 0;
            sb.Children.Add(da);
            Storyboard.SetTarget(da, alertPanel);
            Storyboard.SetTargetProperty(da, new PropertyPath(Grid.OpacityProperty));
            sb.Begin();

            buttonJoinAndStart.IsEnabled = true;
        }

        private bool isPlayWithNoWifi = false;
        private bool hasAskedPlayWithNoWiFi = false;

        private void buttonJoinAndStart_Click(object sender, RoutedEventArgs e)
        {
            if (!Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsWiFiEnabled)
            {
                if (!hasAskedPlayWithNoWiFi)
                {
                    MessageBox.Show("現在、Wi-Fiに接続していません。Wi-Fiに接続しないでジャンケンに突入します");
//                    ToAppearAlertPanel("現在、Wi-Fiに接続していません。Wi-Fiに接続しないでジャンケンに突入しますか？");
                    isPlayWithNoWifi = true;
                    hasAskedPlayWithNoWiFi = true;
                    NavigationService.Navigate(new Uri("/PageJanken.xaml?NavigatedFrom=Main Page", UriKind.Relative));
                }
                if (isPlayWithNoWifi)
                {
                    NavigationService.Navigate(new Uri("/PageJanken.xaml?NavigatedFrom=Main Page", UriKind.Relative));
                }
                else
                {
                    MessageBox.Show("Wi-Fiに接続してから再度このアプリを起動してください");
                }
                return;
            }

            var appSettings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;

            if (!String.IsNullOrWhiteSpace(tbGroupAddress.Text))
            {
                try
                {
                    System.Net.IPAddress.Parse(tbGroupAddress.Text);
                    appSettings[groupaddressKey] = tbGroupAddress.Text;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Multicast Group用のIPアドレスを、IPアドレスフォーマット（xxx.xxx.xxxx.xxxx）で入力してください");
                    return;
                }
            }
            if (!String.IsNullOrWhiteSpace(tbGroupPort.Text))
            {
                UInt16 port;
                if (!UInt16.TryParse(tbGroupPort.Text, out port))
                {
                    MessageBox.Show("Multicast Group用のポート番号を入力してください");
                    return;
                }
                appSettings[groupportKey] = tbGroupPort.Text;
            }
            string pageUri = "/PageJanken.xaml?NavigatedFrom=Main Page";
            if (!String.IsNullOrWhiteSpace(tbGroupName.Text))
            {
                appSettings[groupnameKey] = tbGroupName.Text;
                pageUri += String.Format("&Name={0}", tbGroupName.Text);
            }
            if (!String.IsNullOrWhiteSpace(tbGroupAddress.Text))
            {
                pageUri += String.Format("&Address={0}", tbGroupAddress.Text);
            }
            if (!String.IsNullOrWhiteSpace(tbGroupPort.Text))
            {
                pageUri += String.Format("&Port={0}", tbGroupPort.Text);
            }

            NavigationService.Navigate(new Uri(pageUri, UriKind.Relative));
        }

        private void appBarButtonHelp_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/PageHelp.xaml?NavigatedFrom=Main Page",UriKind.Relative));
        }

        private void buttonAlertOK_Click(object sender, RoutedEventArgs e)
        {
            isPlayWithNoWifi = true;
            hasAskedPlayWithNoWiFi = true;
            ToDisappearAlertPanel();
        }

        private void buttonAlertNG_Click(object sender, RoutedEventArgs e)
        {
            isPlayWithNoWifi = false;
            hasAskedPlayWithNoWiFi = true;
            ToDisappearAlertPanel();
        }
    }
}